#include "bsp_epit.h"

/**
 * @brief
 *
 * @param EPIT_BASE EPIT1_BASE  (0x20D0000u) | EPIT2_BASE (0x20D4000u)
 * @param frac      分频值，范围为0~4095，分别对应1~4096分频。
 * @param value     倒计数值
 */
void EPIT_INIT(EPIT_Type *EPIT, unsigned int frac, unsigned int value) {
  if (frac > 0xfff) {
    frac = 0xfff;
  }
  EPIT->CR = 0;
  EPIT->CR |=
      ((0x1 << 24) | (frac << 4) | (0x1 << 3) | (0x1 << 2) | (0x1 << 1));
  EPIT->LR = value;
  EPIT->CMPR = 0;
}
/**
 * @brief               开启EPIT定时器
 *
 * @param EPIT_BASE     EPIT1_BASE  (0x20D0000u) | EPIT2_BASE (0x20D4000u)
 */
void EPIT_ENABLED(EPIT_Type *EPIT) { EPIT->CR |= (0x1); }
/**
 * @brief               关闭EPIT定时器
 *
 * @param EPIT_BASE     EPIT1_BASE  (0x20D0000u) | EPIT2_BASE (0x20D4000u)
 */
void EPIT_DISABLED(EPIT_Type *EPIT) { EPIT->CR &= ~(0x1); }

/**
 * @brief             设置加载寄存器的值
 *
 * @param EPIT_BASE   EPIT1_BASE  (0x20D0000u) | EPIT2_BASE (0x20D4000u)
 * @param value       32-bit
 */
void EPIT_SET_LR(EPIT_Type *EPIT, unsigned int value) {
  EPIT->CR &= ~(0x1);
  EPIT->LR = value;
  EPIT->CR |= (0x1);
}

/**
 * @brief            使能EPIT中断
 *
 * @param IRQn       EPIT1_IRQn = 88,     < EPIT1 output compare interrupt.
 *                   EPIT2_IRQn = 89, < EPIT2 output compare interrupt.
 */
void EPIT_GIC_EnableIRQ(IRQn_Type IRQn) { GIC_EnableIRQ(IRQn); }

/**
 * @brief             给指定的中断号注册中断服务函数
 *                    EPIT1_IRQn = 88, < EPIT1 output compare interrupt.
 *                    EPIT2_IRQn = 89, < EPIT2 output compare interrupt.
 *
 * @param - irq			  : 要注册的中断号
 * @param - handler		: 要注册的中断处理函数
 * @param - usrParam	: 中断服务处理函数参数
 */
void EPIT_IRQ_HANDLER(IRQn_Type irq, system_irq_handler_t handler,
                      void *userParam) {
  system_register_irqhandler(irq, handler, userParam);
}